#include "pangu.h"

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

static long int GetFileSize(FILE *stream)
{
    long int size;

    fseek(stream, 0L, SEEK_END);
    size = ftell(stream);
    rewind(stream);

    return size;
}

/**
 * @brief   Insert whitespace between Chinese and ASCII character.
 * @note    This function only support utf-8. Formatting GBK codec file may leads to unpredictable error since the
 *          second byte of GBK codec may be range in (0x40-0x7F).
 * @param   file_name: text file name.
 * @retval  0: format successfully, 1: format failed.
 */
int InsertSpace(const char *file_name)
{
    FILE *fp;
    long int file_size;
    int index = 0;
    bool written = false;
    char *buffer;
    int character;
    int prev_character;

    fp = fopen(file_name, "rb");
    if (!fp)
    {
        perror("fopen");
        return EXIT_FAILURE;
    }

    file_size = GetFileSize(fp);
    if (file_size == 0L)  // The file is empty, any operation is unnecessary
    {
        fclose(fp);
        return EXIT_SUCCESS;
    }

    buffer = (char *)malloc(file_size * 2);
    if (buffer == NULL)  // Not enough memory to be allocated
    {
        fclose(fp);
        puts("malloc: No enough memory to be allocated\n");
        return EXIT_FAILURE;
    }

    // Initialize prev_character
    character = fgetc(fp);
    buffer[index++] = character;
    prev_character = character;

    while ((character = fgetc(fp)) != EOF)
    {
        if ((!isascii(prev_character) && isgraph(character)) || (isgraph(prev_character) && !isascii(character)))
        {
            written = true;
            buffer[index++] = 0x20;
        }
        buffer[index++] = character;
        prev_character = character;
    }
    fclose(fp);

    if (written)  // Don't rewrite file if spaces are unnecessary to be inserted
    {
        fp = fopen(file_name, "wb");
        fwrite(buffer, sizeof buffer[0], index, fp);
        fclose(fp);
    }

    free(buffer);
    return EXIT_SUCCESS;
}
